-- Prosody IM
-- Copyright (C) 2012 societe Publica
-- 
-- Authors:
--   Guilhem Lettron <guilhem.lettron@youscribe.com>
-- 
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--

local format  = string.format;

local ldap = module:require 'ldap';
local g_b  = module:require 'groups_bookmarks';

if not ldap then
	module:log("error", "Can't find ldap lib");
	return;
end

if not g_b then
	module:log("error", "Can't find groups_bookmarks lib");
	return;
end

function module.load()
	params = module:get_option('ldap');
	if not params then
		module:log("debug", "no configuration for ldap found");
		return;
	end
	
	module:add_feature("jabber:iq:private");
	module:hook("iq/self/jabber:iq:private:query", g_b.on_connect, 1);
	
	local ld = ldap.getconnection();
	
	if params.rooms then
		local memberfield = params.rooms.memberfield;
		local namefield   = params.rooms.namefield;
		local basedn      = params.rooms.basedn;

		for _, room in ipairs(params.rooms) do
			module:log("debug", "room: %s", tostring(room[namefield]));
			-- Only search the room
			local room_filter = format('%s=%s', namefield, room[namefield]);
			-- Complete by filter if necessary
			if params.rooms.filter then
				room_filter = format('(&(%s)(%s))', params.rooms.filter, room_filter);
			end
			for dn, attrs in ld:search { attrs = { memberfield }, base = basedn, scope = 'subtree', sizelimit = 1, filter = room_filter } do
				local members = attrs[memberfield];
				if members then
					for _, user in ipairs(members) do
						jid = user..'@'..module.host
						module:log("debug", "Add jid %s to room %s", tostring(jid), tostring(room[namefield]));
						g_b.add_user(jid,room[namefield]);
					end
				end
			end
		end
	end
	
	--Manage a flag "room" on groups
	if params.groups then
		memberfield = params.groups.memberfield;
		namefield   = params.groups.namefield;
		basedn      = params.groups.basedn;

		for _, group in ipairs(params.groups) do
			if group['room'] then
				module:log("debug", "room: %s from groups", tostring(group[namefield]));
				local room_filter = format('%s=%s', namefield, group[namefield]);
				if params.rooms.filter then
					room_filter = format('(&(%s)(%s))', params.groups.filter, room_filter);
				end
				for dn, attrs in ld:search { attrs = { memberfield }, base = room_basedn, scope = 'subtree', sizelimit = 1, filter = room_filter } do
					local members = attrs[memberfield];
					if members then
						for _, user in ipairs(members) do
							jid = user..'@'..module.host
							module:log("debug", "Add jid %s to room %s", tostring(jid), tostring(group[namefield]));
							g_b.add_user(jid,group[namefield]);
						end
					end
				end
			end
		end
	end
	
	module:log("info", "group_bookmarks_ldap loaded successfully");
end
